package com.gs.api.core.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author guoyunfei on 2021/9/27 14:48
 * @className RefererInterceptor
 * @description TODO 防止 CSRF跨站请求伪造
 * @Version 1.0
 */
public class RefererInterceptor extends HandlerInterceptorAdapter {

    private final static Logger logger = LoggerFactory.getLogger(RefererInterceptor.class);


    //@Value("${http.referer.ip}")
    private String ipAddress;

    //@Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        String referer = req.getHeader("referer");
        String host = req.getServerName();
        if (referer == null) {
            //TODO  referer 为空状态置为404
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }

        java.net.URL url = null;

        try {
            url = new java.net.URL(referer);
        } catch (MalformedURLException e) {
            //TODO URL解析异常，状态置为404
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }
        logger.debug("method[preHandle] url.getHost():" + url.getHost());
        logger.debug("method[preHandle] ipAddress:" + ipAddress);
        // 首先判断请求域名和referer域名是否相同
        if (!host.equals(url.getHost())) {
            List<String> allowOriginIpList = Arrays.asList(ipAddress.split(","));
            //if (s.equals(url.getHost())) {
                //return true;
            //}
            if (allowOriginIpList.contains(url.getHost())) {
                return true;
            }
            return false;
        }
        return true;
    }

}
